package api

import (
	"alertmanagerWebhook/common"
	"alertmanagerWebhook/config"
	"alertmanagerWebhook/global"
	"fmt"
	"net/smtp"
)

// SendEmail sends an email using SMTP
func SendEmail(subject, body string) error {
	auth := smtp.PlainAuth("", global.Config.Email.Smtp_from, global.Config.Email.Smtp_password, global.Config.Email.Smtp_Host)

	to := []string{global.Config.Email.Smtp_to}
	msg := []byte(fmt.Sprintf("From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n%s", global.Config.Email.Smtp_from, global.Config.Email.Smtp_to, subject, body))

	err := smtp.SendMail(fmt.Sprintf("%s:%d", global.Config.Email.Smtp_Host, global.Config.Email.Smtp_port), auth, global.Config.Email.Smtp_from, to, msg)
	return err
}

// SendToEmail processes the incoming notification and sends appropriate emails.
func SendToEmail(notification config.Notification) {
	if !global.Config.Email.Enabled { // 检查是否启用电子邮件通知
		global.Logger.Infoln("Email notifications are disabled.")
		return
	}

	// Transform the notification into email messages
	emailMessage, err := common.TransformToEmail(notification)
	if err != nil {
		global.Logger.Errorln("Failed to transform notification to email:", err)
		return
	}

	// Send the email using the generated message
	err = SendEmail(emailMessage.Subject, emailMessage.Body)
	if err != nil {
		global.Logger.Errorln("Failed to send email:", err)
	} else {
		global.Logger.Infoln("Email sent successfully.")
	}
}
